﻿using System;
using System.Diagnostics;
using System.Threading;

namespace Landsat8_LSTWindow
{
    public class ToolService
    {
        public event EventHandler OnProgressChanged;
        public void Run(string cmd, string args)
        {
            Process p = new Process();
            p.StartInfo.FileName = cmd;
            p.StartInfo.Arguments = args;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.UseShellExecute = false;

            p.Start();

            p.BeginOutputReadLine();
            p.BeginErrorReadLine();

            p.OutputDataReceived += P_OutputDataReceived;
            p.ErrorDataReceived += P_ErrorDataReceived;

            p.WaitForExit();
            p.Close();
        }

        private void P_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                if (this.OnProgressChanged != null)
                {
                    this.OnProgressChanged(this, new ProgressEventArgs(1, 1, CancellationToken.None) { Message = e.Data });
                }
            }
        }

        private void P_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                if (this.OnProgressChanged != null)
                {
                    this.OnProgressChanged(this, new ProgressEventArgs(1, 1, CancellationToken.None) { Message = e.Data });
                }
            }
        }
    }
}
